//
//  TCLYNewsViewController.m
//  YuErmuYing
//
//  Created by LYang on 16/8/22.
//  Copyright © 2016年 Tiancheng. All rights reserved.
//

#import "TCLYNewsViewController.h"
#import "TCLYNewsTableViewCell.h"
#import "TCLYMineModel.h"
#import "Masonry.h"
#import "Macros.h"
#import "TCLYUser.h"

@interface TCLYNewsViewController () <UITableViewDataSource, UITableViewDelegate,UIAlertViewDelegate>

@property (nonatomic, strong)TCLYMineModel * mineModel;
@property (nonatomic, strong)UITableView * newsTableView;
@property (nonatomic, strong) NSMutableArray * deleteArray;
@property (nonatomic,assign) BOOL edit;
@property (nonatomic, strong)TCLYUser * user;

@end

@implementation TCLYNewsViewController{
    NSMutableArray * cellIndexArr;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.tabBarController.tabBar.hidden = YES;
    self.navigationController.navigationBar.backgroundColor = statusColor;
    self.navigationController.navigationBar.barStyle = UIBarMetricsCompactPrompt;
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, -20, screenWidth, 20)];
    view.backgroundColor = navColor;
    [self.navigationController.navigationBar addSubview:view];
    
    
    UILabel * titleLabel = [[UILabel alloc] init];
    titleLabel.text = @"消息";
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.frame = CGRectMake(0, 0, 50, 20);
    titleLabel.font = [UIFont boldSystemFontOfSize:20];
    self.navigationItem.titleView = titleLabel;
    
    self.deleteArray = [NSMutableArray array];

    self.edit = NO;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(createWork) name:@"loadNewsSucceed" object:nil];
    self.mineModel = [[TCLYMineModel alloc] init];
    self.user = [[TCLYUser alloc] init];
    NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:self.user.userId, @"uid", nil];
    [self.mineModel loadNewsParameters:dic];
    [self createView];
    [self createBtn];

}
-(void) createWork{
    NSLog(@"收到通知%@",self.mineModel.newsArr);
    [self.newsTableView reloadData];
}
-(void) createBtn{
    UIButton * leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame = CGRectMake(12, 22, 20, 20);
    [leftBtn setImage:[UIImage imageNamed:@"left"] forState:UIControlStateNormal];
    leftBtn.tag = 91;
    [leftBtn addTarget:self action:@selector(statusBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    
    UIButton * rightBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    rightBtn.tag = 92;
    [rightBtn setTitle:@"删除" forState:UIControlStateNormal];
    [rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    rightBtn.frame = CGRectMake(screenWidth-12-20, 22, 30, 20);
    [rightBtn addTarget:self action:@selector(deleteAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    
}
-(void) createView{
    self.newsTableView = [[UITableView alloc] init];
    self.newsTableView.backgroundColor = [UIColor colorWithRed:244/255.0 green:244/255.0 blue:244/255.0 alpha:1];
    [self.newsTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    self.newsTableView.delegate = self;
    self.newsTableView.dataSource = self;
    [self.view addSubview:self.newsTableView];
    [self.newsTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
    }];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSLog(@"数组长度%ld",(unsigned long)self.mineModel.newsArr.count);
    NSLog(@"第一个值%@",self.mineModel.newsArr[0]);
    if ([self.mineModel.newsArr[0] isEqual:NULL]) {
        return 0;
    }
    return self.mineModel.newsArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString * identifier = @"newsCell";
    TCLYNewsTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[TCLYNewsTableViewCell alloc] initWithReuseIdentifier:identifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.dayLabel.text = self.mineModel.newsArr[indexPath.row][@"time"];
    cell.contentLabel.text = self.mineModel.newsArr[indexPath.row][@"content"];
    
    if ([self.mineModel.newsArr[indexPath.row][@"status"] isEqual:@"1"]) {
        cell.headerImageView.image = [UIImage imageNamed:@"mineActivity"];
    }
    if ([self.mineModel.newsArr[indexPath.row][@"status"] isEqual:@"2"]) {
        cell.headerImageView.image = [UIImage imageNamed:@"mineIntegral"];
    }
    if ([self.mineModel.newsArr[indexPath.row][@"status"] isEqual:@"3"]) {
        cell.headerImageView.image = [UIImage imageNamed:@"mineIndiana"];
    }
    if (self.edit) {
        int s = 0;
        NSLog(@"%@",self.deleteArray);
        for (int i = 0; i< self.deleteArray.count; i++) {
            if (self.mineModel.newsArr[indexPath.row] == self.deleteArray[i]) {
                UIImageView * selectImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 15, 15)];
                selectImage.image = [UIImage imageNamed:@"mineTick-click"];
                cell.accessoryView = selectImage;
                s = 1;
                cell.accessCount = 1;
            }
        }
        if (s == 0) {
            UIImageView * Image = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 15, 15)];
            Image.image = [UIImage imageNamed:@"mineTic"];
            cell.accessoryView = Image;
            cell.accessCount = 0;
        }
        
        if (self.deleteArray.count < 1) {
            UIImageView * Image = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 15, 15)];
            Image.image = [UIImage imageNamed:@"mineTick-click"];
            cell.accessoryView = Image;
        }
        
        
    }else {
        cell.accessoryView = nil;
    }
    
    return cell;
}


//每个cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 84;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)statusBtnAction:(id)sender{
    switch (((UIButton *)sender).tag) {
        case 91:{
            [self.navigationController popViewControllerAnimated:YES];
            self.navigationController.navigationBarHidden = YES;
            self.tabBarController.tabBar.hidden = NO;
        }
            break;
        case 92:{
            
        }
            break;
    }
}
-(void) deleteNews{
    NSLog(@"刷新");
    NSLog(@"%ld",(unsigned long)self.mineModel.newsArr.count);
    [self.newsTableView reloadData];
}

-(UIImage *)resizeImageWithImage:(UIImage *)image Width:(CGFloat)width Height:(CGFloat)height {
    UIGraphicsBeginImageContext(CGSizeMake(width, height));
    [image drawInRect:CGRectMake(0, 0, width, height)];
    UIImage * newImage = [[UIImage alloc] init];
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

-(void)back:(UIBarButtonItem *)item {
    self.edit = NO;
    
    [self.newsTableView reloadData];
    UIBarButtonItem * item1 = self.navigationItem.rightBarButtonItems[0];
    self.navigationItem.rightBarButtonItems = @[item1];
    self.navigationItem.leftBarButtonItem = nil;
    [self.deleteArray removeAllObjects];
}

-(void)deleteAction:(UIBarButtonItem *)item1 {
    NSLog(@"删除");
    if (self.mineModel.newsArr == nil) {
        return;
    }
    if (self.edit == NO) {
        self.edit = YES;
        UIBarButtonItem * item2 = [[UIBarButtonItem alloc] initWithTitle:@"全选" style:UIBarButtonItemStylePlain target:self action:@selector(SelectAll:)];
        item2.tintColor = [UIColor grayColor];
        self.navigationItem.rightBarButtonItems = @[item1,item2];
        
    UIBarButtonItem * itemLeft = [[UIBarButtonItem alloc] initWithImage:[self resizeImageWithImage:[UIImage imageNamed:@"返回"] Width:25 Height:25] style:UIBarButtonItemStylePlain target:self action:@selector(back:)];
    self.navigationItem.leftBarButtonItem = itemLeft;
        [self.newsTableView reloadData];
    }else if (self.edit == YES && self.deleteArray.count > 0) {
        
        UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"删除消息" message:@"确定要删除所选消息吗?" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"取消");
            [self.deleteArray removeAllObjects];
            UIBarButtonItem * item2 = [[UIBarButtonItem alloc] initWithTitle:@"全选" style:UIBarButtonItemStylePlain target:self action:@selector(SelectAll:)];
            item2.tintColor = [UIColor grayColor];
            self.navigationItem.rightBarButtonItems = @[item1,item2];
            [self.newsTableView reloadData];
        }];
        
        UIAlertAction * action2 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            for (int i = 0; i<self.deleteArray.count; i++) {
                NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:self.user.userId, @"uid", self.deleteArray[i][@"id"], @"id", nil];
                [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteNews) name:@"deleteNewsSucceed" object:nil];
                [self.mineModel deleteNewsParameter:dic];
            }
            
            [self.deleteArray  removeAllObjects];
            self.edit = NO;
            [self.newsTableView reloadData];
            for (NSIndexPath * indexPath in cellIndexArr) {
                TCLYNewsTableViewCell * cell = [self.newsTableView cellForRowAtIndexPath:indexPath];
                cell.accessCount = 0;
            }
        }];
        [alert addAction:action1];
        [alert addAction:action2];
        [self.navigationController presentViewController:alert animated:YES completion:^{
            
        }];
        self.navigationItem.leftBarButtonItem = nil;
        self.navigationItem.rightBarButtonItems = @[item1];
    }else {
        self.edit = NO;
        self.navigationItem.rightBarButtonItems = @[item1];
        [self.newsTableView reloadData];
    }
    
    
}

-(void)SelectAll:(UIBarButtonItem *)item2 {
    item2.tintColor = [UIColor blueColor];
    self.deleteArray = [NSMutableArray arrayWithArray:self.mineModel.newsArr];
    [self.newsTableView reloadData];
}
#pragma mark - 编辑相关
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    TCLYNewsTableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
    if (self.edit && cell.accessCount == 0) {
        cell.accessCount = 1;
        [self.deleteArray addObject:self.mineModel.newsArr[indexPath.row]];
        [cellIndexArr addObject:indexPath];
    }else if (self.edit && cell.accessCount == 1) {
        cell.accessCount = 0;
        for (int i = 0; i < self.deleteArray.count; i++) {
            if (self.deleteArray[i] == self.mineModel.newsArr[indexPath.row]) {
                [self.deleteArray removeObjectAtIndex:i];
                NSLog(@"移除%@",self.deleteArray);
            }
        }
    }
    [self.newsTableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
